package com.vdong.restful.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vdong.data.model.Shipper;
import com.vdong.data.model.Template;
import com.vdong.data.model.TemplateCarryMode;
import com.vdong.data.model.enums.Mode;
import com.vdong.data.model.enums.State;
import com.vdong.data.request.TemplateArea;
import com.vdong.data.service.ShipperService;
import com.vdong.data.service.TemplateService;
import com.vdong.redisutil.distributionredis.target.RedisLock;
import com.vdong.restful.api.request.OrderInformationRequest;
import com.vdong.restful.api.request.TemplateAreaRequest;
import com.vdong.restful.api.request.TemplateCarryModeRequest;
import com.vdong.restful.api.request.TemplateRequest;
import com.vdong.restful.api.response.ExceptionMessage;
import com.vdong.restful.api.response.OrderFreightReponse;
import com.vdong.restful.api.response.Pages;
import com.vdong.restful.api.response.Response;
import com.vdong.restful.util.TemplateToTemplateResponseUtil;
import com.vdong.restful.service.TemplateApiService;
import com.vdong.restful.staticVariable.GlobalStaticVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class TemplateApiServiceImpl implements TemplateApiService {

    private static Logger logger = LoggerFactory.getLogger(TemplateApiServiceImpl.class);


    @Autowired
    private ShipperService shipperService;

    @Autowired
    private TemplateService templateService;

    @Qualifier("ObjectMapper")
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    TemplateToTemplateResponseUtil templateToTemplateResponseUtil;

    @Override
    @RedisLock(value = "#templateRequest.userId")
    public Response add(TemplateRequest templateRequest, String key) {

        Template template = new Template();
        List<ExceptionMessage> lsExceptionMessage = new ArrayList<ExceptionMessage>();
        List<String> templateAreaListCity = new ArrayList<String>();
        Set<String> templateAreaAllset = new HashSet<String>();
        List<TemplateCarryMode> lsTemplateCarryMode = new ArrayList<TemplateCarryMode>();
        List<TemplateArea> templateAreas;
        TemplateCarryMode t;
        TemplateArea ta;
        // 数据转换
        template.setCreateTime(LocalDateTime.now());
        template.setName(templateRequest.getName());
        template.setState(State.OFF);
        template.setUserId(templateRequest.getUserId());
        template.setUsersKey(key);
        for (TemplateCarryModeRequest templateCarryModeRequest : templateRequest.getTemplateCarryModeRequest()) {

            if (templateCarryModeRequest.getMode() == Mode.STANDARD) {
                if (templateCarryModeRequest.getMinAmount() == null) {
                    return Response.failMessage(GlobalStaticVariable.VALIDATION,
                            "运费模式" + Mode.STANDARD + "下minAmount不能为空");
                }
            }

            Shipper shipper = shipperService.findById(templateCarryModeRequest.getShipperId());
            if (shipper == null) {
                lsExceptionMessage.add(ExceptionMessage.putMessage(GlobalStaticVariable.VALIDATION, "没有查询到该快递公司或暂不支持"));
            }
            t = new TemplateCarryMode();
            templateAreas = new ArrayList<>();
            t.setActualAmount(templateCarryModeRequest.getActualAmount());
            t.setMinAmount(templateCarryModeRequest.getMinAmount());
            t.setMode(templateCarryModeRequest.getMode());
            t.setShipperId(templateCarryModeRequest.getShipperId());
            t.setTemplate(template);

            for (TemplateAreaRequest templateArearequest : templateCarryModeRequest.getTemplateAreaRequest()) {
                ta = new TemplateArea();
                ta.setCitiesName(templateArearequest.getCitiesName());
                ta.setProvincesName(templateArearequest.getProincesName());

                templateAreas.add(ta);
                templateAreaListCity.add(templateArearequest.getCitiesName());
                templateAreaAllset.add(templateArearequest.getProincesName() + templateArearequest.getCitiesName());
            }
            if (templateAreas.size() > 0) {

                try {
                    t.setAreas(objectMapper.writeValueAsString(templateAreas));
                } catch (JsonProcessingException e) {
                    return Response.failMessage(GlobalStaticVariable.VALIDATION, "城市省市有非法字符，请重试");
                }

            }
            lsTemplateCarryMode.add(t);

        }

        if (templateAreaListCity.size() != templateAreaAllset.size()) {
            lsExceptionMessage.add(ExceptionMessage.putMessage(GlobalStaticVariable.VALIDATION, "含有重复城市"));
        }

        if (lsExceptionMessage.size() > 0) {
            return Response.fail(lsExceptionMessage);
        } else {

            lsTemplateCarryMode = templateService.save(lsTemplateCarryMode);

            // 查询是否首次
            Template templateOn = templateService.findByUserIdAndState(templateRequest.getUserId(), State.ON, key);
            if (templateOn == null) {
                templateService.updateStatusById(template.getId(), key);
            }
            return Response.successBean(
                    templateToTemplateResponseUtil.templateCarryModeToTemplateResponse(lsTemplateCarryMode));

        }

    }

    @Override
    public Response findByUserId(String userId, Pageable pagebale, String key) {
        Page<Template> ls = templateService.findByUserId(userId, pagebale, key);
        Pages pages = new Pages();
        pages.setNumber(ls.getNumber());
        pages.setSize(ls.getSize());
        pages.setTotalPages(ls.getTotalPages());
        pages.setTotalElements(ls.getTotalElements());

        if (ls.getContent() != null) {
            return Response.successPageList(TemplateToTemplateResponseUtil.toListResponse(ls.getContent()), pages);
        } else {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "匹配失败无数据");
        }

    }

    @Override
    public Response findByUserIdAndState(String userId, State state, String key) {
        Template template = templateService.findByUserIdAndState(userId, State.ON, key);

        if (template != null) {
            return Response.successBean(templateToTemplateResponseUtil.toResponse(template));
        } else {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "匹配失败无数据");
        }
    }

    @Override
    public Response findById(String templateId, String key) {
        Template template = templateService.findById(templateId, key);

        if (template != null) {
            return Response.successBean(templateToTemplateResponseUtil.toResponse(template));
        } else {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "匹配失败无数据");
        }

    }

    public Response freight(OrderInformationRequest orderInformationRequest, String key) {
        OrderFreightReponse orderFreightReponse = new OrderFreightReponse();

        TemplateCarryMode t1 = templateService.findByCitiesNameAndProvincesNameAndTemplateId(
                orderInformationRequest.getRecipientCity(), orderInformationRequest.getRecipientProvince(),
                orderInformationRequest.getUserId(), key);

        if (t1 != null) {

            Shipper shipper = shipperService.findById(t1.getShipperId());
            Template template = t1.getTemplate();
            if (t1.getMode() == Mode.UNIFIED)// 固定
            {
                orderFreightReponse.setActualAmount(t1.getActualAmount());

                orderFreightReponse.setDeductibleAmount(new BigDecimal(0));

            } else if (t1.getMode() == Mode.STANDARD)// 满足包邮
            { // 结果是:-1 小于,0 等于,1 大于免邮

                if (orderInformationRequest.getOrderAmount().compareTo(t1.getMinAmount()) >= 0) {
                    orderFreightReponse.setActualAmount(new BigDecimal(0));
                    orderFreightReponse.setDeductibleAmount(t1.getActualAmount());
                } else {
                    orderFreightReponse.setActualAmount(t1.getActualAmount());
                    orderFreightReponse.setDeductibleAmount(new BigDecimal(0));

                }

            } else {
                return Response.failMessage(GlobalStaticVariable.NO, "暂时没开放");
            }
            orderFreightReponse.setShipperId(shipper.getId());
            orderFreightReponse.setShipperCode(shipper.getCode());
            orderFreightReponse.setShipperName(shipper.getName());
            orderFreightReponse.setOrderId(orderInformationRequest.getOrderId());

            orderFreightReponse.setTemplateId(template.getId());
            // OrderFreight orderFreight = new OrderFreight();
            // orderFreight.setActualAmount(orderFreightReponse.getActualAmount());
            // orderFreight.setCreateTime(LocalDateTime.now());
            // orderFreight.setDeductibleAmount(orderFreightReponse.getDeductibleAmount());
            // orderFreight.setOrderAmount(orderInformationRequest.getOrderAmount());
            // orderFreight.setOrderId(orderInformationRequest.getOrderId());
            // orderFreight.setRecipientCity(orderInformationRequest.getRecipientCity());
            // orderFreight.setUserId(orderInformationRequest.getUserId());
            // orderFreight.setTemplateId(template.getId());
            // orderFreight.setRecipientProvince(orderInformationRequest.getRecipientProvince());
            // orderFreight.setShipperId(shipper.getId());
            // orderFreight.setTemplateCarryModeId(t1.getId());
            // orderFreightService.save(orderFreight);
            return Response.successBean(orderFreightReponse);
        } else {
            logger.info("freight:{}", orderInformationRequest.toString());
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "没有匹配的模板信息");
        }

    }

    public Response saveTemplateStateById(String templateId, String key) {

        int i = templateService.updateStatusById(templateId, key);
        if (i == 1) {
            return Response
                    .successBean(templateToTemplateResponseUtil.toResponse(templateService.findById(templateId, key)));
        } else {
            return Response.failMessage(GlobalStaticVariable.VALIDATION, "没有匹配的信息");
        }

    }

    @Override
    public Response deleteByStateAndId(String templateId, String key) {
        int i = templateService.deleteById(templateId, key);
        if (i == 1) {
            logger.info("delTemplate:{},key{}", templateId, key);
            return Response.successBean(i);
        }
        return Response.failMessage(GlobalStaticVariable.VALIDATION, "删除失败，模板不存在或状态开启");
    }

}
